<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
    
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入街道名称" clearable  style="width: 200px" />
      </el-form-item>
      <el-form-item label="年份" prop="year" >
        <el-date-picker v-model="queryParams.year" format="YYYY" type="year" placeholder="请选择年份 "  style="width: 200px"/>
      </el-form-item>
      <el-form-item label="状态" prop="state" >
        <el-select v-model="queryParams.state" placeholder="请选择状态" style="width: 200px" clearable>
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>
      </el-form-item>
      <el-form-item label="行政区" prop="adminCodeOne">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-select v-model="queryParams.adminCodeOne" placeholder="请选择一级行政区" @change="handleAdminLevelOneChange" style="width: 200px">
              <el-option v-for="dict in administrativeOptions" :key="dict.administrativeCode" :label="dict.administrativeName" :value="dict.administrativeCode">
              </el-option>
            </el-select>
          </el-col>

          <el-col :span="6">
            <el-select v-model="queryParams.adminCodeTwo" placeholder="请选择二级行政区" @change="handleAdminLevelTwoChange" :disabled="!queryParams.adminCodeOne" style="width: 200px">    
              <el-option v-for="dict in administrativeOptionsLevelTwo" :key="dict.administrativeCode" :label="dict.administrativeName" :value="dict.administrativeCode">
              </el-option>
            </el-select>
          </el-col>

          <el-col :span="6">
            <el-select v-model="queryParams.adminCodeThree" placeholder="请选择三级行政区" @change="handleAdminLevelThreeChange" :disabled="!queryParams.adminCodeTwo" style="width: 200px">
              <el-option v-for="dict in administrativeOptionsLevelThree" :key="dict.administrativeCode" :label="dict.administrativeName" :value="dict.administrativeCode">
              </el-option>
            </el-select>
          </el-col>

          <el-col :span="6">
            <el-tree-select v-model="queryParams.adminCodeOther" :data="administrativeOptionsLevelOther" :props="{ value: 'administrativeCode', label: 'administrativeName', children: 'children' }" value-key="administrativeId" placeholder="请选择父级" check-strictly  style="width: 200px"/>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:subCommunity:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['system:subCommunity:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:subCommunity:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:subCommunity:export']">导出</el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="subCommunityList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="街道名称" align="center" prop="name">
      </el-table-column>
      <el-table-column label="省" align="center" prop="province">
      </el-table-column>
      <el-table-column label="市" align="center" prop="city">
      </el-table-column>
      <el-table-column label="区" align="center" prop="district">
      </el-table-column>
      <el-table-column label="状态" align="center" prop="state">
        <template #default="scope">
          <el-tag :type="scope.row.state === '0' ? 'info' : scope.row.state === '1' ? 'warning' : 'success'">{{ showState(scope.row)  }}</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="街道数" align="center" prop="subCommunityCount">
      </el-table-column> -->
      <el-table-column label="行政区域" align="center" prop="administrativeRegion">
      </el-table-column>
      <el-table-column label="楼栋数" align="center" prop="buildingCount">

      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:subCommunity:edit']">修改</el-button>
          <el-button v-if="scope.row.state === '1'" link type="primary" icon="Checked" @click="handleExamine(scope.row)" v-hasPermi="['system:subCommunity:edit']">审核</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:subCommunity:remove']">删除</el-button>
          <el-button link type="primary" icon="Delete" @click="openView(scope.row)" v-hasPermi="['system:subCommunity:remove']">预览</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改sub_community对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <viewPage ref="viewPageRef" @getList="getList" />
  </div>
</template>

<script setup name="subCommunity" >
// 获取当前Vue组件实例
const { proxy } = getCurrentInstance()
// 导入Vue相关函数
import { ref, reactive, toRefs, getCurrentInstance, watch } from 'vue';
import { listSubCommunity, delSubCommunity, addSubCommunity, updateSubCommunity } from "@/api/system/subCommunity"
import { getFormconfig } from "@/api/system/formconfig"
import { EBuilder } from "epic-designer";
import viewPage from "./view.vue"
// 导入行政区划相关的API接口
import { listAdministrative, listAdministrativeByTree } from "@/api/system/administrative";
// 表格数据
const subCommunityList = ref([])
// 弹窗是否打开
const open = ref(false)
// 加载状态
const loading = ref(true)
// 搜索框是否显示
const showSearch = ref(true)
// 选中的行数据
const ids = ref([])
// 单选择
const single = ref(true)
// 多选择
const multiple = ref(true)
// 总条数
const total = ref(0)
// 弹窗标题
const title = ref("")
const options = [
  {
    value: '0',
    label: '暂存',
  },
  {
    value: '1',
    label: '未审核',
  },
  {
    value: '2',
    label: '已审核',
  },

]
// 表单设计器配置
const pageSchema =null;
// 预览弹窗组件引用
// const viewRef = ref<InstanceType<typeof viewPage>>()
// 预览弹窗组件实例引用
const viewPageRef = null
// 各级行政区划选项数据
const administrativeOptions = ref([])
const administrativeOptionsLevelTwo = ref([])
const administrativeOptionsLevelThree = ref([])
const administrativeOptionsLevelOther = ref([])
// 获取表单设计器组件引用
// const designerRef = ref<InstanceType<typeof EBuilder>>(any);
const data = reactive({
  formData: {},
  form: {
    buildingCount: null,
    city: null,
    communityCount: null,
    createBy: null,
    createTime: null,
    delFlag: null,
    district: null,
    formConfigId: null,
    formConfigType: null,
    formDataId: null,
    formDataName: null,
    id: null,
    name: null,
    province: null,
    state: null,
    // subCommunityCount: null,
    updateBy: null,
    updateTime: null,
    administrativeRegion: null,
    adminCodeOne: '',
    adminCodeTwo: '',
    adminCodeThree: '',
    adminCodeOther: '',
    year: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    buildingCount: null,
    city: null,
    communityCount: null,
    district: null,
    formConfigId: null,
    formConfigType: null,
    formDataId: null,
    formDataName: null,
    name: null,
    province: null,
    state: null,
    // subCommunityCount: null,
    administrativeRegion: '',
    adminCodeOne: '',
    adminCodeTwo: '',
    adminCodeThree: '',
    adminCodeOther: '',
    year: null
  },
  rules: {
    id: [
      { required: true, message: "街道不能为空", trigger: "blur" }
    ],
  }
})
//
const { queryParams, form, rules } = toRefs(data)

/** 查询sub_community列表 */
function getList() {
  loading.value = true
  if (queryParams.value.adminCodeOther) {
    queryParams.value.administrativeRegion = queryParams.value.adminCodeOther
  } else if (queryParams.value.adminCodeThree) {
    queryParams.value.administrativeRegion = queryParams.value.adminCodeThree
  } else if (queryParams.value.adminCodeTwo) {
    queryParams.value.administrativeRegion = queryParams.value.adminCodeTwo
  } else if (queryParams.value.adminCodeOne) {
    queryParams.value.administrativeRegion = queryParams.value.adminCodeOne
  } else {
    queryParams.value.administrativeRegion = ''
  }

  console.log("queryParams.value.administrativeRegion", queryParams.value)
  listSubCommunity(queryParams.value).then((response) => {
    subCommunityList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    buildingCount: null,
    city: null,
    communityCount: null,
    createBy: null,
    createTime: null,
    delFlag: null,
    district: null,
    formConfigId: null,
    formConfigType: null,
    formDataId: null,
    formDataName: null,
    id: null,
    name: null,
    province: null,
    state: null,
    // subCommunityCount: null,
    updateBy: null,
    updateTime: null,
    administrativeRegion: null,
    adminCodeOne: '',
    adminCodeTwo: '',
    adminCodeThree: '',
    adminCodeOther: '',
    year: null

  }
  proxy.resetForm("subCommunityRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()

   proxy.$refs.viewPageRef.onOpen({}, "add")
}
/** 预览按钮操作 */
function openView(row) {
  console.log(row)
  if (!row.id) {
    proxy.$modal.msgError("请选择数据在进行操作")
    return
  }
 
  proxy.$refs.viewPageRef.onOpen(row, "view")


}
function showState(row) {
  if (row.state == 0) {
    return '暂存'
  } else if (row.state == 1) {
    return '未审核'
  } else if (row.state == 2) {
    return '已审核'
  }

}

/** 修改按钮操作 */
function handleUpdate(row) {
  // reset()
  proxy.$refs.viewPageRef.onOpen(row, "update")
} function handleExamine(row) {
  // reset()
  proxy.$refs.viewPageRef.onOpen(row, "examine")
}

/** 提交按钮 */
function submitForm() {
  handleValidate()
  proxy.$refs["subCommunityRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateSubCommunity(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addSubCommunity(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除"' + row.name + '"的数据项？').then(function () {
    return delSubCommunity(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/subCommunity/export', {
    ...queryParams.value
  }, `街道填报_${new Date().getTime()}.xlsx`)
}
// 校验表单数据
async function handleValidate() {
  if (designerRef.value) {
    data.formData = { ...(await designerRef.value.getData()) }
    console.log(data.formData)
  }
}
/** 获取表单配置JSON */
function getFormConfigJson(ID) {
  console.log(ID)
  if (designerRef.value) {
    getFormconfig(ID).then((response) => {
      // 设置表单数据
      console.log(response.data.formJson)
      // form.value.year = JSON.stringify(form.value.year);
      // 设置表单设计器数据
      // designerRef.value?.setData(JSON.parse(response.data.formJson))
      pageSchema.value = JSON.parse(response.data.formJson);
      // 设置对话框标题

    }).finally(() => {
      // 取消加载状态
      loading.value = false
    })
  }
}
// 监听行政区划数据变化，初始化一级数据
watch(administrativeOptions, (newVal) => {
  if (newVal && newVal.length > 0) {
    // 初始化一级数据
    administrativeOptionsLevelTwo.value = []
    administrativeOptionsLevelThree.value = []
    administrativeOptionsLevelOther.value = []
  }
})
/** 加载表单 */
function loadFormSchemaData() {
  if (designerRef.value) {
    data.formData = { "input_tlmiftms": "test3244" }

  }



}
/** 加载行政区划数据 */
function getlistAdministrative(parentCode) {
  console.log('getlistAdministrative', parentCode)
  listAdministrative({ parentCode: parentCode }).then((response) => {
    administrativeOptions.value = []
    administrativeOptions.value = response.data
    console.log('getlistAdministrative', parentCode, administrativeOptions.value)
  })
};
// 一级行政区变更事件
function handleAdminLevelOneChange(value) {
  // 清空后续级别的选择
  form.value.adminCodeTwo = ''
  form.value.adminCodeThree = ''
  form.value.adminCodeOther = ''

  // 根据一级行政区获取二级行政区数据
  if (value) {
    listAdministrative({ parentCode: value }).then((response) => {
      console.info("🚀 ~ file:index method: line:573 -----", response)
      administrativeOptionsLevelTwo.value = []
      administrativeOptionsLevelTwo.value = response.data
    })
  } else {
    administrativeOptionsLevelTwo.value = []
  }

  // 清空三级及以下数据
  administrativeOptionsLevelThree.value = []
  administrativeOptionsLevelOther.value = []
}

// 二级行政区变更事件
function handleAdminLevelTwoChange(value) {

  // 清空后续级别的选择
  form.value.adminCodeThree = ''
  form.value.adminCodeOther = ''
  // 根据二级行政区获取三级行政区数据
  if (value) {
    listAdministrative({ parentCode: value }).then((response) => {
      administrativeOptionsLevelThree.value = []
      administrativeOptionsLevelThree.value = response.data
    })
  } else {
    administrativeOptionsLevelThree.value = []
  }
  // 清空详细级数据
  administrativeOptionsLevelOther.value = []
}

// 三级行政区变更事件
function handleAdminLevelThreeChange(value) {
  // 清空详细级别的选择
  form.value.adminCodeOther = ''

  // 根据三级行政区获取详细行政区数据
  if (value) {
    listAdministrativeByTree({ parentCode: value }).then((response) => {
      // 清空选项数组
      administrativeOptionsLevelOther.value = []
      // 创建顶级节点数据
      administrativeOptionsLevelOther.value = response.data
    })
  } else {
    administrativeOptionsLevelOther.value = []
  }
}
// 初始化方法
function init() {
  // 初始化行政区划数据
  getlistAdministrative('0');
  //加载列表数据
  getList()
}

init()

</script>
